<?php

class myUser extends sfBasicSecurityUser
{
	public function login($openid_url, Array $params = array())
	{
		$user = Doctrine_Core::getTable('User')
		->findOneBy('id_arise', $openid_url);
			
		if ($user == null)
		{
			// Create user in DB
			$newuser = new User();
			$newuser->setIdArise($openid_url);
			$newuser->setFirstname(array_key_exists('firstname', $params) ? $params['firstname'] : $openid_url);
			$newuser->setLastname(array_key_exists('lastname', $params) ? $params['lastname'] : $openid_url);
			$newuser->setNickname(array_key_exists('nickname', $params) ? $params['nickname'] : $openid_url);
			$newuser->save();

			// Authenticating user
			$this->setAuthenticated(true);
			$this->setAttribute('id_arise', 	$newuser->getIdArise());
			$this->setAttribute('id', 			$newuser->getPrimaryKey());
			$this->setAttribute('firstname', 	$newuser->getFirstname());
			$this->setAttribute('lastname', 	$newuser->getLastname());
			$this->setAttribute('nickname', 	$newuser->getNickname());

			$admin = (array_key_exists('admin', $params)) ? $params['admin'] : false;
			if ($admin) $this->addCredential('admin');
		}
		else
		{
			// Mise à jour des infos de l'utilisateur
			
			$user->setFirstname(array_key_exists('firstname', $params) ? $params['firstname'] : $user->getFirstname());
			$user->setLastname(array_key_exists('lastname', $params) ? $params['lastname'] : $user->getLastname());
			$user->setNickname(array_key_exists('nickname', $params) ? $params['nickname'] : $user->getNickname());
			$user->save();
			
			// Authenticating user
			$this->setAuthenticated(true);
			$this->setAttribute('id_arise', 	$user->getIdArise());
			$this->setAttribute('id', 			$user->getPrimaryKey());
			$this->setAttribute('firstname', 	$user->getFirstname());
			$this->setAttribute('lastname', 	$user->getLastname());
			$this->setAttribute('nickname', 	$user->getNickname());
			
			$admin = (array_key_exists('admin', $params)) ? $params['admin'] : false;
			if ($admin) $this->addCredential('admin');
		}
	}

	public function logout()
	{
		$this->setAuthenticated(false);
		$this->clearCredentials();
		$this->getAttributeHolder()->clear();
	}
}
